package com.gitlab.bootren.data.core.query;

import org.apache.commons.lang3.StringUtils;

/**
 * 组合条件
 *
 * @author Administrator
 *
 */
class CombCondition extends AbstractCondition {

    /**
     * 条件1
     */
    protected ICondition m1;

    /**
     * 条件2
     */
    protected ICondition m2;

    /**
     * 组合方式
     */
    protected CombType combType = CombType.AND;

    public CombCondition(ICondition m1, ICondition m2) {
        this.m1 = appendSubConditionParam(m1);
        this.m2 = appendSubConditionParam(m2);

    }

    private ICondition appendSubConditionParam(ICondition m) {
        if (m instanceof KvCondition) {
            KvCondition kv = (KvCondition) m;
            kv = kv.copy();
            String paramName = kv.getParamName();
            while (this.getParams().containsKey(paramName)) {
                paramName += "1";
            }
            kv.setParamName(paramName);

            this.params.put(paramName, kv.getParams().values().iterator().next());

            return kv;
        }
        this.params.putAll(m.getParams());
        return m;
    }

    public CombCondition(ICondition m1, ICondition m2, CombType combType) {
        this(m1, m2);
        this.combType = combType;

    }

    @Override
    public String ql() {
        String q1 = m1.toQl();
        String q2 = m2.toQl();
        if(m2 instanceof Condition){
            if(StringUtils.isNotEmpty(q2)){
                q2 = "( "+q2+" )";
            }
        }
        return mergeQl(q1, q2);

    }

    @Override
    public String ql(String aliasName) {
        String q1 = m1.toQl(aliasName);
        String q2 = m2.toQl(aliasName);
        if(m2 instanceof Condition){
            if(StringUtils.isNotEmpty(q2)){
                q2 = "( "+q2+" )";
            }
        }
        return mergeQl(q1, q2);
    }

    private String mergeQl(String q1, String q2) {
        String q = "";

        if (q1.length() > 0) {
            q += q1;
        }
        if (q2.length() > 0) {
            if (q1.length() > 0) {
                q += " " + this.combType.getValue() + " ";
            }

            q += q2;
        }
        return q;
    }

}
